<template>
	<view class="">
		<!-- 使用自定义导航组件 -->
		<custom-navbar title="成为伙伴" :showBack="true"></custom-navbar>
	</view>
	<view class="recruitment-form-container">
		<!-- 	<view class="form-header">
			<text class="form-title">招聘申请表</text>
		</view> -->

		<uni-forms ref="form" :model="formData" :rules="rules" class="form-content">
			<!-- 个人信息 -->
			<view class="form-section">

				<uni-forms-item label="" name="name">
					<view class="label-container">
						<text class="label-text">您的姓名</text>
						<text class="required-mark">*</text>
					</view>
					<input class="form-input" v-model="formData.name" placeholder="请输入姓名" />
				</uni-forms-item>

				<uni-forms-item label="" name="gender">
					<view class="label-container">
						<text class="label-text">性别</text>
					</view>
					<view class="radio-group">
						<radio-group @change="e => formData.gender = e.detail.value">
							<label style="display: inline-block;">
								<radio :checked="formData.gender === '男'" value="男" />男
							</label>
							<label style="display: inline-block;">
								<radio :checked="formData.gender === '女'" value="女" />女
							</label>
						</radio-group>
					</view>
				</uni-forms-item>

				<uni-forms-item label="" name="birthdate">
					<view class="label-container">
						<text class="label-text">出生日期</text>
					</view>
					<uni-datetime-picker type="date" v-model="formData.birthdate" :start="'1950-01-01'"
						:end="new Date().toISOString().split('T')[0]" format="yyyy-MM-dd" @change="birthDateChange"
						placeholder="请选择出生日期" class="form-datetime-picker" />
				</uni-forms-item>

				<uni-forms-item label="" name="phone">
					<view class="label-container">
						<text class="label-text">联系电话</text>
						<text class="required-mark">*</text>
					</view>
					<input class="form-input" v-model="formData.phone" type="tel" maxlength="11" placeholder="请输入联系电话"
						@input="formatPhoneNumber" />
					<text v-if="!validationStatus.phone.isValid"
						class="validation-error">{{ validationStatus.phone.message }}</text>
				</uni-forms-item>

				<uni-forms-item label="" name="wechat">
					<view class="label-container">
						<text class="label-text">您的微信</text>
					</view>
					<input class="form-input" v-model="formData.wechat" type="text" placeholder="请输入您的微信" />
				</uni-forms-item>
			</view>

			<!-- 请简单介绍一下你自己-->
			<view class="form-section">
				<text class="section-title">二、请简单介绍一下你自己</text>


				<!-- 	<uni-forms-item label="" name="college">
					<view class="label-container">
						<text class="label-text">最高学历院校</text>
					</view>
					<input class="form-input" v-model="formData.college" placeholder="请输入最高学历院校" />
				</uni-forms-item> -->
				<!-- <uni-forms-item label="" name="edu_start_time">
					<view class="label-container">
						<text class="label-text">在校时段（开始）</text>
					</view>
					<uni-datetime-picker type="date" v-model="formData.edu_start_time" :start="'1950-01-01'"
						:end="new Date().toISOString().split('T')[0]" format="yyyy-MM-dd" placeholder="请选择在校时段"
						class="form-datetime-picker" />
				</uni-forms-item> -->

				<!-- <uni-forms-item label="" name="edu_end_time">
					<view class="label-container">
						<text class="label-text">在校时段（结束）</text>
					</view>
					<uni-datetime-picker type="date" v-model="formData.edu_end_time"
						:start="formData.edu_start_time || '1950-01-01'" :end="'2050-12-31'" format="yyyy-MM-dd"
						placeholder="请选择在校时段" class="form-datetime-picker" />
				</uni-forms-item> -->

				<!-- <uni-forms-item label="" name="major">
					<view class="label-container">
						<text class="label-text">毕业专业</text>
					</view>
					<input class="form-input" v-model="formData.major" placeholder="请输入毕业专业" />
				</uni-forms-item> -->

				<!-- <uni-forms-item label="" name="education">
					<view class="label-container">
						<text class="label-text">最高学历背景</text>
					</view>
					<view class="radio-group">
						<radio-group @change="e => formData.education = e.detail.value">
							<label style="display: inline-block; margin-right: 30rpx;">
								<radio :checked="formData.education === '高中'" value="高中" />高中
							</label>
							<label style="display: inline-block; margin-right: 30rpx;">
								<radio :checked="formData.education === '大专'" value="大专" />大专
							</label>
							<label style="display: inline-block; margin-right: 30rpx;">
								<radio :checked="formData.education === '本科'" value="本科" />本科
							</label>
							<label style="display: inline-block; margin-right: 30rpx;">
								<radio :checked="formData.education === '硕士'" value="硕士" />硕士
							</label>
							<label style="display: inline-block;">
								<radio :checked="formData.education === '博士'" value="博士" />博士
							</label>
						</radio-group>
					</view>
				</uni-forms-item> -->
				<uni-forms-item label="" name="experience">
					<view class="label-container">
						<text class="label-text">擅长的领域</text>

					</view>
					<textarea class="form-textarea" v-model="formData.experience" placeholder="请输入擅长的领域（选填）"
						@input="onExperienceInput" maxlength="300" />
					<text class="char-count">
						{{ formData.experience.length }}/300字
					</text>
				</uni-forms-item>


			</view>

			<!-- 您希望分享的资质或荣誉 -->
			<view class="form-section">
				<text class="section-title">三、您希望分享的资质或荣誉</text>

				<!-- 上传提示信息 -->
				<view class="upload-tips">
					<text class="tips-text">请上传您希望分享的资质受训背景或荣誉，最多可上传6张。</text>
				</view>

				<view class="certificate-upload">
					<view class="upload-item" v-for="(file, index) in formData.cards" :key="index">
						<image v-if="file.url && ['jpg', 'jpeg', 'png'].includes(file.type)" :src="getOSSUrl(file.url)"
							mode="aspectFit"></image>
						<view v-else-if="file.url" class="file-item">
							<text class="file-icon">📄</text>
							<text class="file-name">{{ file.name }}</text>
							<text class="file-size">{{ formatFileSize(file.size) }}</text>
						</view>
						<view class="delete-btn" @click.stop="deleteCertificate(index)">×</view>
					</view>
					<view v-if="formData.cards.length < 6" class="upload-btn" @click="chooseCertificate">
						<text class="upload-plus">+</text>
						<text class="upload-text">点击上传荣誉</text>
					</view>
				</view>

				<!-- 文件数量提示 -->
				<view class="file-count-tip">
					<text class="count-text">已上传 {{ formData.cards.length }}/6 个文件</text>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="form-footer">
				<button @click="submitForm" type="primary" class="submit-btn">申请成为伙伴</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	// 根据实际安装的组件，导入存在的uni-ui组件
	import uniForms from '@dcloudio/uni-ui/lib/uni-forms/uni-forms.vue'
	import uniFormsItem from '@dcloudio/uni-ui/lib/uni-forms-item/uni-forms-item.vue'
	import uniDatetimePicker from '@dcloudio/uni-ui/lib/uni-datetime-picker/uni-datetime-picker.vue'
	import customNavbar from '../../components/custom-navbar/custom-navbar.vue';
	// 导入API接口
	import {
		submitRecruitmentForm,
		uploadImageForAgency,
		deleteOSSFileForAgency
	} from '../../api/api.js'
	import {
		getOSSUrl
	} from '../../utils/oss.js'
	import {
		getUserInfo
	} from '../../utils/auth.js'

	// 其他基础表单组件是uni-app内置的，不需要从uni-ui导入
	export default {
		components: {
			uniForms,
			uniFormsItem,
			uniDatetimePicker
		},
		computed: {
			getOSSUrl() {
				return getOSSUrl;
			}
		},
		data() {
			return {
				// 表单数据
				formData: {
					// 机构id
					uid: '0',
					aid: '',
					// 个人信息
					name: '',
					gender: '男',
					// 出生日期
					birthdate: '',
					// 电话号码
					phone: '',
					wechat: '',
					// 教育背景（支持多条）
					edu_start_time: '',
					edu_end_time: '',
					// 院校名称
					college: '',
					// 专业
					major: '',
					// 学历
					education: '',
					// 相关经历
					experience: '',
					// 相关证书
					cards: []
				},
				// 验证状态
				validationStatus: {
					phone: {
						isValid: true,
						message: ''
					}
				},
				// 表单验证规则
				rules: {
					// 个人信息模块 - 仅姓名和手机号必填
					name: [{
						required: true,
						errorMessage: '请输入您的姓名'
					}],
					phone: [{
						required: true,
						errorMessage: '请输入联系电话'
					}, {
						pattern: /^1[3-9]\d{9}$/,
						errorMessage: '请输入正确的手机号码'
					}],
					// education: [{
					// 	required: true,
					// 	errorMessage: '请选择最高学历背景'
					// }],

					// 相关经历字段 - 完全非必填
					experience: [{
						required: false
					}]
				}
			}
		},
		onLoad(options) {
			console.log(options, 'options');
			// 保存分享ID
			this.formData.aid = options.id;
			const userInfo = getUserInfo();
			if (!userInfo || userInfo.id === 'null') {
				this.formData.uid = '0';
			} else {
				this.formData.uid = userInfo.id;
			}
			

			console.log(this.formData.aid, 'this.formData.aid----');
		},
		methods: {
			// 处理出生日期变更
			birthDateChange(e) {
				// For uni-datetime-picker, the value is directly in the event object
				this.formData.birthdate = e;
			},

			// 格式化手机号码输入并添加实时验证
			formatPhoneNumber(e) {
				// 处理不同环境的事件对象结构
				let value = e.detail ? e.detail.value : (e.target ? e.target.value : e);
				// 只保留数字
				value = value.replace(/\D/g, '');
				// 限制长度为11位
				if (value.length > 11) {
					value = value.slice(0, 11);
				}

				this.formData.phone = value;

				// 实时验证手机号码格式
				if (value === '') {
					// 空值不显示错误
					this.validationStatus.phone.isValid = true;
					this.validationStatus.phone.message = '';
				} else if (value.length < 11) {
					// 长度不足11位
					this.validationStatus.phone.isValid = false;
					this.validationStatus.phone.message = '请输入完整的11位手机号码';
				} else {
					// 使用正则表达式验证格式
					const phoneRegex = /^1[3-9]\d{9}$/;
					if (!phoneRegex.test(value)) {
						this.validationStatus.phone.isValid = false;
						this.validationStatus.phone.message = '请输入正确的手机号码格式';
					} else {
						this.validationStatus.phone.isValid = true;
						this.validationStatus.phone.message = '';
					}
				}
			},

			// 处理相关经历输入
			onExperienceInput() {
				// 确保experience属性存在
				if (!this.formData.experience) {
					this.formData.experience = '';
				}
				// 验证字数范围
				if (this.formData.experience.length < 200) {
					// 字数不足时的处理
				}
			},

			// 选择证书文件
			chooseCertificate() {
				uni.chooseMessageFile({
					count: 6 - this.formData.cards.length, // 最多可选择的文件数量
					extype: 'file',
					extension: ['jpg', 'jpeg', 'png', 'pdf'],
					success: (res) => {
						const tempFiles = res.tempFiles;
						// 检查文件类型
						for (let i = 0; i < tempFiles.length; i++) {
							const file = tempFiles[i];
							const fileExtension = file.name.split('.').pop().toLowerCase();

							// 检查文件类型是否支持
							if (!['jpg', 'jpeg', 'png', 'pdf'].includes(fileExtension)) {
								uni.showToast({
									title: `文件${file.name}类型不支持，请上传jpg、png或pdf格式`,
									icon: 'none'
								});
								continue;
							}

							// 上传文件
							this.uploadFile(file, fileExtension);
						}
					}
				});
			},

			// 上传文件
			uploadFile(file, fileExtension) {
				uni.showLoading({
					title: '上传中...'
				});

				// 调用上传接口
				uploadImageForAgency(file.path, 'certificate').then(result => {
					uni.hideLoading();

					// 检查返回结果是否包含url
					// 注意：新的STS上传返回的url是key路径，不含域名前缀
					if (result && result.url) {
						// 将文件信息添加到cards数组
						this.formData.cards.push({
							id: Date.now() + '_' + Math.random().toString(36).substr(2, 9), // 生成唯一ID
							name: file.name,
							size: file.size,
							type: fileExtension,
							url: result.url // 这里是OSS key路径，不含域名前缀
						});

						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '上传失败，返回数据格式不正确',
							icon: 'none'
						});
					}
				}).catch(error => {
					uni.hideLoading();
					console.error('上传失败:', error);
					uni.showToast({
						title: error.message || '上传失败，请重试',
						icon: 'none'
					});
				});
			},

			// 删除证书
			async deleteCertificate(index) {
				try {
					// 获取要删除的文件信息
					const fileInfo = this.formData.cards[index]

					// 显示确认对话框
					const res = await new Promise((resolve) => {
						uni.showModal({
							title: '确认删除',
							content: '确定要删除此证书吗？',
							confirmText: '删除',
							cancelText: '取消',
							success: resolve
						})
					})

					if (res.confirm) {
						// 用户确认删除，调用OSS删除接口
						uni.showLoading({
							title: '删除中...'
						})

						await deleteOSSFileForAgency(fileInfo.url)

						// 从本地数组中移除
						this.formData.cards.splice(index, 1)

						uni.hideLoading()
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('删除证书失败:', error)

					// 即使OSS删除失败，也从本地数组中移除（避免界面异常）
					this.formData.cards.splice(index, 1)

					uni.showToast({
						title: '删除失败，但已从列表中移除',
						icon: 'none'
					})
				}
			},

			// 格式化文件大小
			formatFileSize(bytes) {
				if (bytes === 0) return '0 Bytes';
				const k = 1024;
				const sizes = ['Bytes', 'KB', 'MB', 'GB'];
				const i = Math.floor(Math.log(bytes) / Math.log(k));
				return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
			},

			// 手动重置表单数据
			resetFormData() {
				this.formData = {
					// 保留机构id
					uid: this.formData.uid || '0',
					// 个人信息
					aid: this.formData.aid,
					name: '',
					gender: '男',
					birthdate: '',
					phone: '',
					wechat: '',
					// 教育背景
					edu_start_time: '',
					edu_end_time: '',
					college: '',
					major: '',
					education: '',
					experience: '',
					// 相关证书
					cards: []
				};

				// 重置验证状态
				this.validationStatus = {
					phone: {
						isValid: true,
						message: ''
					}
				};
			},


			// 提交表单
			submitForm() {
				this.$refs.form.validate().then(res => {

					// 验证成功，处理表单数据
					console.log('表单数据：', this.formData)

					// 调用提交到服务器的方法
					this.submitToServer(this.formData)

				}).catch(err => {
					// 验证失败
					// console.log('表单验证失败：', err)
					uni.showToast({
						title: '请检查表单填写',
						icon: 'none'
					})
				})
			},

			// 提交到服务器
			submitToServer(data) {
				// 显示加载提示
				uni.showLoading({
					title: '提交中...'
				})

				// 调用API提交表单数据
				return submitRecruitmentForm(data).then(res => {
					// 隐藏加载提示
					uni.hideLoading()

					// 显示成功提示
					uni.showToast({
						title: '您的信息已成功提交至机构相关负责人，后续请等待机构相关人员与您联系。',
						icon: 'success'
					})

					// 重置表单 - 手动重置表单数据，因为resetFields方法不存在
					this.resetFormData()

					// 可以选择返回上一页或跳转到其他页面
					// setTimeout(() => {
					//   uni.navigateBack()
					// }, 1500)

					return res
				}).catch(err => {
					// 隐藏加载提示
					uni.hideLoading()

					// 显示错误提示 - 确保传入的是字符串
					uni.showToast({
						title: err.message || '提交失败，请重试',
						icon: 'none'
					})

					throw err
				})
			}
		}
	}
</script>

<style scoped>
	/* 必填字段样式 */
	.label-container {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.label-text {
		font-size: 28rpx;
		color: #303133;
	}

	.required-mark {
		color: #e64340;
		margin-left: 4rpx;
		font-size: 28rpx;
	}

	.recruitment-form-container {
		padding: 20rpx 20rpx 60rpx 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
		margin-top: 190rpx;
	}

	.form-header {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.form-title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
	}

	.form-content {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 10rpx;
	}

	.form-section {
		margin-bottom: 40rpx;
	}

	.section-title {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 2rpx solid #eee;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #eee;
		border-radius: 8rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
	}

	.validation-error {
		display: block;
		color: #e64340;
		font-size: 24rpx;
		margin-top: 8rpx;
	}

	.form-textarea {
		width: 100%;
		height: 160rpx;
		border: 2rpx solid #eee;
		border-radius: 8rpx;
		padding: 20rpx;
		box-sizing: border-box;
		resize: none;
		background-color: #fff;
	}

	.radio-group {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
	}

	.radio-group label {
		margin-right: 40rpx;
		display: flex;
		align-items: center;
	}

	.education-item,
	.work-item {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		font-weight: bold;
		color: #666;
	}

	.add-btn {
		width: 100%;
		margin-top: 10rpx;
		margin-bottom: 20rpx;
	}

	.form-footer {
		margin-top: 40rpx;
	}

	.submit-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 32rpx;
	}

	.form-input {
		background-color: #fff;
	}

	.form-datetime-picker {
		background-color: #fff;
		width: 100%;
	}

	/* 相关经历字数统计样式 */
	.char-count {
		display: block;
		text-align: right;
		font-size: 24rpx;
		color: #666;
		margin-top: 8rpx;
	}

	/* 证书上传样式 */
	.upload-tips {
		background-color: #f0f7ff;
		border-left: 4rpx solid #409eff;
		padding: 16rpx 20rpx;
		margin-bottom: 20rpx;
		border-radius: 0 8rpx 8rpx 0;
	}

	.tips-text {
		font-size: 26rpx;
		color: #606266;
		line-height: 1.5;
	}

	.certificate-upload {
		padding: 20rpx 0;
		display: flex;
		flex-wrap: wrap;
		align-items: flex-start;
	}

	.upload-item {
		display: inline-block;
		position: relative;
		width: 150rpx;
		height: 180rpx;
		margin-right: 24rpx;
		margin-bottom: 24rpx;
		border: 1px solid #e4e7ed;
		border-radius: 8rpx;
		overflow: hidden;
		background-color: #fafafa;
		transition: all 0.3s ease;
	}

	.upload-item:hover {
		border-color: #409eff;
		box-shadow: 0 2rpx 12rpx 0 rgba(0, 0, 0, 0.1);
	}

	.upload-item image {
		width: 100%;
		height: 100%;
	}

	.file-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		padding: 10rpx;
		box-sizing: border-box;
		text-align: center;
	}

	.file-icon {
		font-size: 48rpx;
		margin-bottom: 8rpx;
	}

	.file-name {
		font-size: 22rpx;
		color: #303133;
		text-align: center;
		word-break: break-all;
		line-height: 1.3;
		margin-bottom: 4rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.file-size {
		font-size: 18rpx;
		color: #909399;
		text-align: center;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		background-color: rgba(230, 67, 64, 0.8);
		color: white;
		font-size: 28rpx;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
		line-height: 40rpx;
		border-radius: 0 0 0 8rpx;
		transition: background-color 0.3s;
	}

	.delete-btn:hover {
		background-color: rgba(230, 67, 64, 1);
	}

	.upload-btn {
		display: inline-block;
		width: 150rpx;
		height: 180rpx;
		border: 2rpx dashed #dcdfe6;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #fafafa;
		transition: all 0.3s;
	}

	.upload-btn:hover {
		border-color: #409eff;
		background-color: #ecf5ff;
	}

	.upload-plus {
		font-size: 48rpx;
		color: #c0c4cc;
		line-height: 1;
		margin-bottom: 8rpx;
	}

	.upload-text {
		font-size: 22rpx;
		color: #c0c4cc;
		text-align: center;
		padding: 0 8rpx;
	}

	.upload-btn:hover .upload-plus,
	.upload-btn:hover .upload-text {
		color: #409eff;
	}

	.file-count-tip {
		margin-top: 16rpx;
		text-align: right;
	}

	.count-text {
		font-size: 24rpx;
		color: #909399;
	}
</style>